<?php
set_time_limit(0);
error_reporting(E_ALL ^ E_NOTICE);

include './vendor/autoload.php';
include './func/code.php';
include './func/func.php';


// 搜索列表备案
function run()
{
	echo '开始:'.PHP_EOL;
	$start = microtime(true);
	$links = input_data();

	foreach ($links as $key => $item) {

		list($title, $domain, $icp) = $item;
		echo "{$domain} \t查询中...".PHP_EOL;

		$info = valid($domain);

		$info['link'] = "{$title},{$domain},{$icp}";
		
		output_data($info);
	}
	$end = microtime(true);
	echo 'Done!'.PHP_EOL;
	echo '用时:'.sec2time($end-$start).PHP_EOL;
}
run();


// 搜索备案号
function valid($domain = 'baidu.com')
{
	// 获取 cookie
	$base = 'http://www.miitbeian.gov.cn/icp/publish/query/icpMemoInfo_showPage.action';
	$html = http($base);

	// 获取验证码
	$code_url  = 'http://www.miitbeian.gov.cn/getVerifyCode?';
	// 校对验证码
	$valid_url = 'http://www.miitbeian.gov.cn/common/validate/validCode.action';
	$valid = false;
	$text  = '';


	// 识别验证码直到正确
	do {
		// 获取图片
		$file = down($code_url.mt_rand(5, 100));
		$file = @imagecreatefromstring($file);

		sleep(3);
		if (!is_resource($file)) {
			echo '验证码图片下载失败!!!'.PHP_EOL;
			continue;
		}


		// 处理图片
		$path = image_one($file);


		// 识别图片 code fontyp num eng
		$text = (new TesseractOCR($path))->lang('eng')->psm(7)->run();
		$text = code_replace($text);
		if (strlen($text) != 6 || $text == false) {
			continue;
		}


		// 验证码校验
		$res   = http($valid_url, ['validateValue'=>$text]);
		$valid = json_decode($res, true);
		$valid = $valid['result'];

	} while (!$valid);


	// 执行查询
	$exec =	'http://www.miitbeian.gov.cn/icp/publish/query/icpMemoInfo_searchExecute.action';
	$args = [
		'siteName'=>'',
		'condition'=>'1',
		'siteDomain'=>$domain,
		'siteUrl'=>'',
		'mainLicense'=>'',
		'siteIp'=>'',
		'unitName'=>'',
		'mainUnitNature'=>-1,
		'certType'=>-1,
		'mainUnitCertNo'=>'',
		'verifyCode'=>$text
	];

	// 返回结果
	$html = http($exec, $args);
	$html = iconv('GBK', 'UTF-8', $html);
	return get_info($html);
}


function test()
{
	// $path = __DIR__.'/images/color.png';
	// $img = imagecreatefromjpeg($path);
	// $img = image_one($img);
	// exit;

	$name = __DIR__.sprintf('/char%02d.png', 1);
	$text = (new TesseractOCR($name))->lang('eng')->psm(8)->run();
	echo $text.PHP_EOL;
}


// test();







